#include <stdbool.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100

int contents[STACK_SIZE];
int top = 0;

void make_empty(void);
bool is_empty(void);
bool is_full(void);
void push(char);
int pop(void);
int calculate(char);

int main()
{
    char c;
    int temp_result;

    for (;;) {
        printf("Enter an RPN expression: ");
        while ((c = getchar()) != '\n' && top < STACK_SIZE){
            if (isdigit(c))
                push(c - '0');
            else if (c == '=') {
                printf("Value of expression: %d\n", pop());
            } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                temp_result = calculate(c);
                push(temp_result);
            } else if (c == ' ') {
                continue;
            } else {
                exit(0);
            }
        }
    }

    return 0;
}

int calculate(char operator)
{   
    int first = pop(), second = pop();      //前一个操作数，前第二个操作数
    // printf("前一个操作数是%d，前二个操作数是%d\n", first, second);
    switch(operator){
        case '+':
            return first + second;
        case '-':
            return second - first;
        case '*':
            return first * second;
        case '/':
            return second / first;
        default:
            return 0;
    }
}

void make_empty(void)
{
    top = 0;
}

bool is_empty(void)
{
    return top == 0;
}

bool is_full(void)
{
    return top == STACK_SIZE;
}

void push(char c)
{
    if (is_full())
        printf("stack overflow");
    else
        contents[top++] = c;
}

int pop(void)
{
    if (is_empty())
        return '\n';
    else
        return contents[--top];   
}
